from django.shortcuts import render,HttpResponse
from rest_framework.viewsets import ViewSetMixin
from rest_framework.generics import ListAPIView
from .models import Banner
from .serializer import BannerSerializer
from django.conf import settings  # 这个是django的配置文件：优先用项目的配置信息，如果没有，使用内置(即这里dev)
from django.core.cache import cache
from rest_framework.response import Response


class BannerView(ViewSetMixin,ListAPIView):
    queryset = Banner.objects.filter(is_delete=False,is_show=True,).order_by('orders')[:settings.BANNER_COUNT]
    serializer_class = BannerSerializer

    def list(self, request, *args, **kwargs):
        # 先去缓存中获取，如果缓存有，直接返回，如果没有，去数据库查询，放到缓存

        # 先去缓存中获取
        banner_list = cache.get('banner_list_cache')
        if not banner_list:  # 去数据库中获取
            # 没有走缓存
            print('查了数据库')
            res = super().list(request, *args, **kwargs)
            banner_list = res.data  # res是Response对象
            # 放入到缓存中
            cache.set('banner_list_cache', banner_list)
        return Response(data=banner_list)


def index(request):
    print(request.method)
    print('put执行了')
    return HttpResponse('ssss')